import type { UserState } from './types';
import type { LoginReq } from '@/api/user/types';
import { defineStore } from 'pinia';
import { UserApi } from '@/api';
import AccountCacheManager from '@/utils/accountCache';

import { clearToken, setToken } from '@/utils/auth';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: '',
    userInfo: undefined,
  }),
  getters: {
    // 兼容性 getters - 从 userInfo 中提取字段
    user_id: (state: UserState) => state.userInfo?.id?.toString() || '',
    user_name: (state: UserState) => state.userInfo?.name || '',
    name: (state: UserState) => state.userInfo?.name || '',
    mobile: (state: UserState) => state.userInfo?.mobile || '',
    real_name: (state: UserState) => state.userInfo?.admin?.real_name || '',
    dangkou_name: (state: UserState) => state.userInfo?.admin?.real_name || '',
    dangkou_address: (state: UserState) => state.userInfo?.admin?.address || '',
    dangkou_phone: (state: UserState) => state.userInfo?.admin?.phone || '',
    area: (state: UserState) => state.userInfo?.admin?.area || '',
    multiple_merchants: (state: UserState) => state.userInfo?.multiple_merchants || 0,
    merchant_id: (state: UserState) => state.userInfo?.merchant_id || null,
    print: (state: UserState) => state.userInfo?.print || {},

    // 从缓存获取多商户信息
    multipleMerchantsInfo: (state: UserState) => {
      if (!state.userInfo?.mobile) return [];
      return AccountCacheManager.getMerchants(state.userInfo.mobile) || [];
    },
  },
  actions: {
    // 设置用户的信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      const result = await UserApi.profile();
      this.setInfo(result);
    },
    // 异步登录并存储token
    login(loginForm: LoginReq) {
      return new Promise((resolve, reject) => {
        UserApi.login(loginForm).then(async (res) => {
          if (res.code === 200) {
            const { token } = res.data;
            const { info } = res.data;

            // 检查是否为多账户响应
            if (Array.isArray(info)) {
              // 多账户情况，直接返回响应，不设置用户信息
              resolve(res);
              return;
            }

            // 单账户情况，设置token
            if (token) {
              setToken(token);
            }

            // 调用 getUserInfoByToken 接口获取用户信息
            try {
              const userInfoRes = await UserApi.getUserInfoByToken({ token });
              if (userInfoRes.data) {
                // 存储完整的用户信息
                this.setInfo({
                  token,
                  userInfo: userInfoRes.data,
                });

                // 将多商户信息存储到缓存
                if (userInfoRes.data.multiple_merchants_info && userInfoRes.data.mobile) {
                  AccountCacheManager.saveMerchants(userInfoRes.data.mobile, userInfoRes.data.multiple_merchants_info);
                }
              }
              resolve(res);
            }
            catch (error) {
              console.error('获取用户信息失败:', error);
              // 如果获取用户信息失败，清除token并抛出错误
              clearToken();
              reject(new Error('获取用户信息失败'));
            }
          }
          else {
            reject(new Error(res.msg || '登录失败'));
          }
        }).catch((error) => {
          reject(error);
        });
      });
    },
    // Logout
    async logout() {
      await UserApi.logout();
      this.resetInfo();
      clearToken();
      // 清除多账户缓存
      AccountCacheManager.clearCache();
    },
    // 清除过期缓存（在登录失败或token过期时调用）
    clearExpiredCache() {
      AccountCacheManager.clearCache();
    },
    // 小程序授权登录
    async authLogin(code: string) {
      const res = await UserApi.loginByCode({ code });
      if (res.code === 200) {
        // 检查是否为多账户响应
        if (Array.isArray(res.data)) {
          // 多账户情况，直接返回响应，不设置用户信息
          return res;
        }

        // 检查data是否包含info数组（多账户格式）
        if (res.data && Array.isArray(res.data.info)) {
          // 多账户情况，直接返回响应，不设置用户信息
          return res;
        }

        // 单账户情况，设置token和用户信息
        if (res.data?.token) {
          setToken(res.data.token);
        }

        // 调用 getUserInfoByToken 接口
        if (res.data?.token) {
          try {
            const userInfoRes = await UserApi.getUserInfoByToken({ token: res.data.token });
            // 设置用户信息
            if (userInfoRes.data) {
              this.setInfo({
                token: res.data.token,
                userInfo: userInfoRes.data,
              });
            }
          }
          catch (error) {
            console.error('调用 getUserInfoByToken 接口失败:', error);
          }
        }
        return res;
      }
    },
    // 微信多商户登录
    async wxMultiMerchantLogin(phone: string, id: number) {
      const res = await UserApi.wxLogin({ phone, id });
      if (res.code === 200 && res.data?.token) {
        // 设置token
        setToken(res.data.token);

        // 调用 getUserInfoByToken 接口获取用户信息
        try {
          const userInfoRes = await UserApi.getUserInfoByToken({ token: res.data.token });
          if (userInfoRes.data) {
            this.setInfo({
              token: res.data.token,
              userInfo: userInfoRes.data,
            });
          }
        }
        catch (error) {
          console.error('调用 getUserInfoByToken 接口失败:', error);
        }
      }
      return res;
    },
    // 获取买家信息
    async getUserInfo(maijia_id: number) {
      return await UserApi.getUserInfo({ maijia_id });
    },
  },
  persist: true,
});

export default useUserStore;
